//
//  RegisterVC.m
//  SH_JSK
//
//  Created by duwl on 1/27/15.
//  Copyright (c) 2015 asiainfo. All rights reserved.
//

#import "RegisterViewController.h"
#import "CommonMacro.h"
#import "UIImage+LXX.h"
#import "RegisterNextViewController.h"



@interface RegisterViewController ()<UITextFieldDelegate>
{
    UIButton *checkBtn;
    BOOL ifPhoneNum;
    NSString *mycheck;
}
@property(nonatomic,strong)UITextField *phoneNum;
@property(nonatomic,strong)UITextField *checkNum;
@property(nonatomic,strong)NSString *ifFind;
- (BOOL)isMobileNumber:(NSString *)mobileNum;
@end

@implementation RegisterViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    _ifFind = @"0";
    //设置导航栏背景颜色
    [self.navigationController.navigationBar setBarTintColor:[GetFileModel colorWithHexString:@"#34bd81" alpha:1]];
    //设置导航栏字体颜色
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];    //左边按钮
//    UIBarButtonItem *laft = [[UIBarButtonItem alloc]
//                             initWithTitle:@"登录"
//                             style:UIBarButtonItemStylePlain
//                             target:self
//                             action:@selector(baby)];
//    [laft setTintColor:[UIColor whiteColor]];
//    self.navigationItem.leftBarButtonItem = laft;
    //自定义左右按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"_0000_返回.png"]
                      forState:UIControlStateNormal];
    [button addTarget:self action:@selector(baby)
     forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, 20, 15);
    
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.leftBarButtonItem = menuButton;

    
    self.title = @"注册";//设置navigationbar上显示的标题
    
    if (IS_OS_7_OR_LATER) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
}


-(void)baby{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.navigationController) {
        self.navigationController.navigationBarHidden = NO;
    }
}

- (void)loadView
{
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.view.backgroundColor = [UIColor whiteColor];
    [self layout];
}

-(void)layout
{
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self.view addGestureRecognizer:tap];
    
    bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:bgView];
    
    UIView *registView = [[UIView alloc]initWithFrame:CGRectMake(20,150, SCREEN_WIDTH-40, 110)];
    [bgView addSubview:registView];
    registView.layer.cornerRadius = 8;
    registView.layer.borderColor = UIColorWithRGBA(232, 234, 237, 1).CGColor;
    registView.layer.borderWidth = 1;
    
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 60, SCREEN_WIDTH-40, 1)];
    line.backgroundColor = UIColorWithRGBA(232, 234, 237, 1);
    
    UIImageView *phoneImg = [[UIImageView alloc]initWithFrame:CGRectMake(20,25, 12,20)];
    phoneImg.image = [UIImage imageNamed:@"_0002s_0005_手机@2x"];
    [registView addSubview:phoneImg];
    
    UIImageView *checkImg = [[UIImageView alloc]initWithFrame:CGRectMake(20,75,15,20)];
    checkImg.image = [UIImage imageNamed:@"_0001s_0000s_0002_验证码@2x"];
    [registView addSubview:checkImg];
    
    
    _phoneNum = [[UITextField alloc]initWithFrame:CGRectMake(60, 20, SCREEN_WIDTH-40, 35)];
    _phoneNum.delegate = self;
    _phoneNum.placeholder = @"请输入手机号码";
    _phoneNum.keyboardType = UIKeyboardTypeNumberPad;

    
    _checkNum = [[UITextField alloc]initWithFrame:CGRectMake(60, 70, 200, 35)];
    _checkNum.delegate = self;
    _checkNum.placeholder = @"请输入验证码";
    [registView addSubview:_phoneNum];
    [registView addSubview:_checkNum];
    [registView addSubview:line];
    
//    UIButton *nextTepBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 300, SCREEN_WIDTH-40, 50)];
//    //    UIImage* image = [UIImage resizedImage:@"bg_green_button.9"];
//    nextTepBtn.layer.cornerRadius = 8;
//    nextTepBtn.backgroundColor = [GetFileModel colorWithHexString:@"#34bd81" alpha:1];
//    [nextTepBtn setTitle:@"下一步" forState:UIControlStateNormal];
//    [nextTepBtn addTarget:self action:@selector(nextTep) forControlEvents:UIControlEventTouchUpInside];
//    [bgView addSubview:nextTepBtn];
    
    UIButton * btnClick = [UIButton buttonWithType:UIButtonTypeCustom];
    btnClick.frame = CGRectMake(20, 300, SCREEN_WIDTH-40, 50);
    [btnClick setBackgroundImage:[UIImage imageNamed:@"gree@2x"] forState:UIControlStateNormal];
    [btnClick setBackgroundImage:[UIImage imageNamed:@"greeScl@2x"] forState:UIControlStateHighlighted];
    [btnClick setTitle:@"下一步" forState:UIControlStateNormal];
    [btnClick setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnClick.titleLabel.textAlignment = NSTextAlignmentCenter;
    [btnClick addTarget:self action:@selector(nextTep) forControlEvents:UIControlEventTouchUpInside];
    btnClick.userInteractionEnabled = YES;
    [bgView addSubview:btnClick];

    
    
    checkBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-140, 70, 90, 35)];
    //   [checkBtn setBackgroundImage:image forState:UIControlStateNormal];
    [checkBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [checkBtn addTarget:self action:@selector(checkClicked) forControlEvents:UIControlEventTouchUpInside];
    checkBtn.layer.cornerRadius = 8;
    checkBtn.titleLabel.font = [UIFont systemFontOfSize:12];
//    checkBtn.backgroundColor = UIColorWithRGBA(89,214,158,1);
    [checkBtn setTintColor:[UIColor blackColor]];
    [checkBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [registView addSubview:checkBtn];
}


- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178
     * 联通号段: 130,131,132,155,156,185,186,145,176
     * 电信号段: 133,153,180,181,189,177
     */
    
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178
     */
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177
     */
    NSString *CT = @"^1(33|53|77|8[019])\\d{8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

-(void)nextTep
{
//    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
//    NSString *myString = [userDefaultes stringForKey:@"mycheck"];
    //此处发送请求
//    ////NSLog(@"checNum为%@",myString);

    if(_phoneNum.text.length!=11) {
        
        [self ShowProgressHUDwithMessage:@"请输入11位手机号码！"];
    }
 else  if ([_checkNum.text isEqualToString:mycheck]) {

         RegisterNextViewController *regist = [[RegisterNextViewController alloc]init];
//     regist.ifFind = _ifFind;
         regist.phoneNum = _phoneNum.text;
         regist.checkCode = _checkNum.text;
         [self.navigationController pushViewController:regist animated:YES];
   }
    
 else if ([_checkNum.text isEqualToString:mycheck]==FALSE) {
     [self ShowProgressHUDwithMessage:@"验证码输入有误！"];
 }
}

-(void)checkClicked
{
    if(_phoneNum.text.length==0) {
        [self ShowProgressHUDwithMessage:@"请输入手机号码!"];
    }

    if(_phoneNum.text.length>0) {
        if(![self isMobileNumber:_phoneNum.text]) {
            [self ShowProgressHUDwithMessage:@"手机号码不合法!"];
        }
 
        else{
            
            NSDictionary *param = @{@"phoneNumber": _phoneNum.text,@"codeType": @"1"};
            
            [UserDAL getCheckNum:param withBlock:^(NSString *checkNum, NSError *error) {
                if (checkNum) {
//                    [self showSimpleAlertView:checkNum];
                    mycheck = checkNum;
                }
                if (error) {
                    [JKAlert showMessage:@"提示" message:@"网络请求失败"];
                }
            }];
            //此处发送请求
            __block int timeout=60; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [checkBtn setTitle:@"免费获取短信验证码" forState:UIControlStateNormal];
                        checkBtn.userInteractionEnabled = YES;
                    });
                }else{
                    int seconds = timeout%181;
                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [checkBtn setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                        checkBtn.userInteractionEnabled = NO;
                        
                    });
                    timeout--;
                    
                }
            });
            dispatch_resume(_timer);
        }

    }
    
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    bgView.frame = CGRectMake(0, -100, SCREEN_WIDTH, SCREEN_HEIGHT);
    //NSLog(@"111");
    
    
}
- (void)tap:(UITapGestureRecognizer *)recognizer
{
    //NSLog(@"222");

    bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

    [_phoneNum resignFirstResponder];
    [_checkNum resignFirstResponder];
}

-(void)showSimpleAlertView:(NSString*)message
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark - HUD
- (void)ShowProgressHUDwithMessage:(NSString *)msg
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = msg;
    hud.dimBackground = NO;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1];
}


@end
